package org.willthink.controller;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.catalina.Session;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import org.willthink.service.member.MemberService;

@Controller
@RequestMapping("/member")
public class MemberController {

	private MemberService service;

	public void setService(MemberService service) {
		this.service = service;
	}
	
	@RequestMapping(value="/login.think")
	public String viewLoginPage(){
		
		return "member/memberLogin";
	}
	
	@RequestMapping(value="/loginProcess.think")
	public ModelAndView loginProcess(HttpServletRequest request, HttpServletResponse response){
		ModelAndView mav = new ModelAndView();
		Map<String, String> map = new HashMap<String, String>();
		String memberId = request.getParameter("memberId");
		String password = request.getParameter("password");
		HttpSession session = null;
		map.put("memberId", memberId);
		map.put("password", password);
		
		Map<String, String> userInfo = null;
		try {
			userInfo = service.memberLogin(map);
			if(userInfo != null){
				System.out.println(userInfo.toString());
				session = request.getSession();
				session.setAttribute("member", userInfo);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		mav.setView(new RedirectView("/main/mainView.think"));
		return mav;
	}
	
	@RequestMapping(value="/logoutProcess.think")
	public ModelAndView logoutProcess(HttpServletRequest request, HttpServletResponse response){
		ModelAndView mav = new ModelAndView();
		HttpSession session = request.getSession();
		session.removeAttribute("member");
		
		mav.setView(new RedirectView("/main/mainView.think"));
		return mav;
	}
}
